/**
 * 
 */
package com.android.hw.projectmenu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.text.TextUtils;
import android.util.Log;
import com.qualcomm.qcnvitems.QcNvItems;
import android.os.SystemProperties;
/**
 * @author gaoshengpan
 *
 */
public class ShVersionInfo extends PreferenceActivity {
     private static final String KEY_HW_VERSION = "hw_version";
     private static final String KEY_BOOT_VERSION = "boot_version";
     private static final String KEY_BOOTCOMP_TIME = "bootcomp_time";
     private static final String KEY_AP_VERSION = "ap_version";
     private static final String KEY_APCOM_TIME = "apcom_time";
     private static final String KEY_CP_VERSION = "cp_version";
     private static final String KEY_CPCOM_TIME = "cpcom_time";
     private static final String KEY_APEFS_VERSION = "apefs_version";
     private static final String KEY_APEFSCOM_TIME = "apefscom_time";
     private static final String KEY_CPEFS_VERSION = "cpefs_version";
     private static final String KEY_CPEFSCOM_TIME = "cpefscom_time";
     private static final String KEY_CUST_VERSION = "cust_version";
     private static final String FILENAME_PROC_VERSION = "/proc/version";
     private QcNvItems mNv;
     private static String mUnknown = null;
     private static boolean mHideVersionName = false;
     private static String TAG = "ShVersionInfo";
     
     
     private Handler mHandler = new Handler() {

         @Override
         public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {

            case 0:
                
                break;
            case 1:
                setSummaryText(KEY_CP_VERSION, modemSN());
                break;
            default:
                break;
            }
         }
      };


    /**
     * 
     */
    public ShVersionInfo() {
        // TODO Auto-generated constructor stub
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.shversion_info);
         mNv = new QcNvItems(this);
    }
    
	public static String readFile(String filePath) {
		String res = "";
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new FileInputStream(new File(filePath))));
			String str = null;
			while ((str = br.readLine()) != null) {
				res += str;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}
    
    /* (non-Javadoc)
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        setPreferenceSummary();
    }
    
    public void setPreferenceSummary() {

		Log.d(TAG, "set -----:" + "hh");
		setSoftwareVersion();
		try {
			setSummaryText(KEY_HW_VERSION,
					readFile("/sys/devices/soc0/hw_pcbboard_version"));
		} catch (Exception e) {
			// TODO: handle exception
		}
		setSummaryText(KEY_BOOT_VERSION, getFormattedKernelVersion(0));
		setSummaryText(KEY_BOOTCOMP_TIME, getFormattedKernelVersion(1));
		setInfoUseQcNVItems();

	}
 
   
    private void setInfoUseQcNVItems(){
        if (mNv == null) {
            mNv = new QcNvItems(this);
        }
        if(mNv != null){
         Log.d(TAG, "send message -----:"+"hh");
         mHandler.sendEmptyMessage(1);
         }
    }
    
    public static String formatKernelVersion(String rawKernelVersion,int i) {
        // Example (see tests for more):
        // Linux version 3.0.31-g6fb96c9 (android-build@xxx.xxx.xxx.xxx.com) \
        //     (gcc version 4.6.x-xxx 20120106 (prerelease) (GCC) ) #1 SMP PREEMPT \
        //     Thu Jun 28 11:02:39 PDT 2012

        final String PROC_VERSION_REGEX =
            "Linux version (\\S+) " + /* group 1: "3.0.31-g6fb96c9" */
            "\\((\\S+?)\\) " +        /* group 2: "x@y.com" (kernel builder) */
            "(?:\\(gcc.+? \\)) " +    /* ignore: GCC version information */
            "(#\\d+) " +              /* group 3: "#1" */
            "(?:.*?)?" +              /* ignore: optional SMP, PREEMPT, and any CONFIG_FLAGS */
            "((Sun|Mon|Tue|Wed|Thu|Fri|Sat).+)"; /* group 4: "Thu Jun 28 11:02:39 PDT 2012" */
        Log.d(TAG,"--->"+rawKernelVersion);
    	Log.d(TAG,Pattern.compile(PROC_VERSION_REGEX).toString());
        Matcher m = Pattern.compile(PROC_VERSION_REGEX).matcher(rawKernelVersion);
        if (!m.matches()) {
            Log.e(TAG, "Regex did not match on /proc/version: " + rawKernelVersion);
            return "Unavailable";
        } else if (m.groupCount() < 4) {
            Log.e(TAG, "Regex match on /proc/version only returned " + m.groupCount()
                    + " groups");
            return "Unavailable";
        }

        if (i==0) {
        	 return m.group(1);
        } else {
            /*return m.group(1) + "\n" +                 // 3.0.31-g6fb96c9
                m.group(2) + " " + m.group(3) + "\n" + // x@y.com #1
                m.group(4);    */                        // Thu Jun 28 11:02:39 PDT 2012
        	return m.group(4);
        }
    }

    /**
     * Reads a line from the specified file.
     * @param filename the file to read from
     * @return the first line, if any.
     * @throws IOException if the file couldn't be read
     */
    private static String readLine(String filename) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filename), 256);
        try {
//            Log.d(TAG,"readLine--------->"+reader.readLine());
            String version = reader.readLine();
            return version;
        } finally {
            reader.close();
        }
    }
    private static String getFormattedKernelVersion(int i) {
        try {
            Log.d(TAG,"getFormattedKernelVersion----11111----->"+formatKernelVersion(readLine(FILENAME_PROC_VERSION),0));
            return formatKernelVersion(readLine(FILENAME_PROC_VERSION),i);

        } catch (IOException e) {
            Log.e(TAG,
                "IO Exception when getting kernel version for Device Info screen",
                e);

            return "Unavailable";
        }
    }

    private void setSoftwareVersion() {
        String softwareTitle = getSystemproString("ro.build.display.id");
        /*gaoshenpan 15-08-20 fix ap-comptime begin*/
        String softwareTime = getSystemproString("ro.build.date");
        /*gaoshenpan 15-08-20 fix ap-comptime end*/
        Log.d(TAG,"softwareTime------->"+softwareTime);
        /*gaoshenpan 15-11-10 fix just use ro.build.date as ap-comptime & no need split begin*/
       /* if (softwareTime.length() > 18) {
            int nPos = softwareTime.indexOf(".");
            nPos = softwareTime.indexOf(".", nPos);
            softwareTime = softwareTime.substring(nPos + 1);
            Log.d(TAG,"softwareTime------->1"+softwareTime);
            nPos = softwareTime.indexOf(".");
            nPos = softwareTime.indexOf(".", nPos);

            softwareTime = softwareTime.substring(nPos + 1);
            Log.d(TAG,"softwareTime------->2"+softwareTime);

            StringBuffer time = new StringBuffer(softwareTime);
            time.insert(4, '-');
            time.insert(7, '-');
            time.replace(10, 11, " ");
            time.insert(13, ':');
            time.insert(16, ':');
            softwareTime = time.toString();
        }*/
        /*gaoshenpan 15-11-10 fix just use ro.build.date as ap-comptime & no need split end*/
        setSummaryText(KEY_AP_VERSION, softwareTitle);
        setSummaryText(KEY_APCOM_TIME, softwareTime);

    }
    
    private static String getSystemproString(String property) {
        return SystemProperties.get(property, "unknown");
    }
    private String modemSN() {
        String sn = null;
        if (mNv == null) {
            mNv = new QcNvItems(this);
        }
        if(mNv != null){
        try {
        	/*15-09-07 gaoshenpan  fix modem_number begin */
            sn = mNv.getSNNumber().substring(32);
           /*15-09-07 gaoshenpan  fix modem_number end */
            Log.d(TAG, "readSN -----:" + sn);
        } catch (Exception e) {
            // TODO: handle exception
            Log.e(TAG, "getSN e:" + e);
        }
        Log.e(TAG, "getSN info :" + sn);
          }
        return sn;
    }

     private void setSummaryText(String preferenceKey, String value) {
            Preference preference = findPreference(preferenceKey);
            if (preference == null)
                return;

            if (TextUtils.isEmpty(value))
                preference.setSummary(mUnknown);
            else
                preference.setSummary(value);
        }
}
